import { getMatchList, getMatchClassDel } from '../../api/match.js'
import { deepClone } from '../../utils/deepClone.js'
import { removeObj } from '../../utils/removeObj.js'
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    searchValue:'',//搜索框的值
    showToastState:true,//是否已加载全部
    navHeight:'128',
    tabHeight:'',
    firstLoading:true,
    navTop: 66,
    array: [],//分类选择
    index: 0,//分类选中下表
    searchValue:'',
    total:0, //列表总数
    list: [],
    multiIndex: [0, 0, 0],
    multiArray: [],
    pageNum: 1,
    pageSize:8,
    isRequst: false,//用来判断当前是否为请求状态
    showLoading:true,
    time: {
      start: 180, // 开始时间是今天的前180天
      end: 730 // 结束时间是今天的730天后 （2年）
    },
    start: '2020-01-01',
    end: '2023-09-01',
    showSelectState: false, // 显示筛选项
    selectTop:137, // 筛选项上面留空高度
    yearArr:[],
    searchArr: [0, -1, -1, -1, -1, -1, -1]
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let { start, end } = this.data.time
    let day1 = new Date().valueOf();
    let startTime = new Date(day1 - (24 * 60 * 60 * 1000 * start));
    let endTime = new Date(day1 + (24 * 60 * 60 * 1000 * end));
    let start1 = startTime.getFullYear() + '-' + (startTime.getMonth() + 1) + '-' + startTime.getDate();
    let end1 = endTime.getFullYear() + '-' + (endTime.getMonth() + 1) + '-' + endTime.getDate();
    this.setData({ start: start1, end: end1})
      // , navHeight: app.globalData.navHeight * 2, tabHeight: app.globalData.navHeight * 2 - app.globalData.navTop 
    // wx.createSelectorQuery().select('.choosebox').boundingClientRect(bottomRect => {
    //   this.setData({ navTop: bottomRect.top - this.data.navTop - 10 })
    // }).exec()
    // wx.createSelectorQuery().select('.filter').boundingClientRect(bottomRect => {
    //   this.setData({ selectTop: bottomRect.top })
    // }).exec()
    this.setData({ yearArr: [new Date().getFullYear() - 1, new Date().getFullYear()]})
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.feach(false)
  },
  //筛选条件变化时重置以下数据
  feach(state = true) {
    this._getMatchClassDel(() => {
      app._getAddressInfo(data => {
        this.setData({multiArray: data[0], firstLoading: true, index: 0,multiIndex: [0, 0, 0]})
        if (this.data.list.length==0){
          this.setData({ searchArr: [0, -1, -1, -1, -1, -1, -1]})
        }
        this.setCurrencyData(state)
      })
    })
  },
  //设置通用数据重置
  setCurrencyData(state) {
    this.setData({isRequst: false, showToastState: true })
    if (state) {
      this.setData({ pageNum: 1})
    }
    this._getMatchList()
  },
  clearValue(){
    this.setData({ searchValue:''})
    this.setCurrencyData()
  },
  _getMatchClassDel(callback) {
    if (this.data.array.length == 0) {
      getMatchClassDel().then(res => {
        this.setData({ array: removeObj(res.data, ['searchValue', 'createBy', 'createTime', 'updateBy', 'updateTime', 'remark', 'params', 'sort', 'recommendHome']) })
        callback()
      })
    }else{
      callback()
    }
  },
  changeData(e){
    this.setData({ list: e.detail})
  },
  // 获取赛程列表
  _getMatchList: function () {
    if (!this.data.isRequst) {
      this.setData({ isRequst: true })
      let { pageNum, pageSize, date, searchArr, yearArr, list, array, multiIndex, multiArray, firstLoading, showLoading, showToastState, searchValue} = this.data
      let obj = { pageNum, pageSize, currentData: searchArr[0] == 0 ? 1 : 2}
      if (searchArr[1] != -1) { obj.progress = searchArr[1]==0?1:2 } // 报名状态
      if (searchArr[2] != -1) { obj.categoryId = array[searchArr[2]].categoryId } // 赛事项目
      if (searchArr[3] != -1) { // 举办地区
        let address = multiArray[0][searchArr[3]];
        if (searchArr[4]!=-1){
          address += ',' + multiArray[1][searchArr[4]];
        }
        obj.shortAddress = address
      } 
      if (searchValue != '') { // 搜索关键词
        obj.nameOrAddress = searchValue
      } 
      if (searchArr[5] != -1) { obj.timeStart = yearArr[searchArr[5]] + (searchArr[6] != -1 ? ('/' + Number(searchArr[6] + 1)) : '') } // 举办时间
      if(showToastState){
        getMatchList(obj,showLoading).then(res => {
          if (res.rows.length > 0) {
            let arr = res.rows;
            this.setData({ list: (pageNum == 1 ? arr : [...list, ...arr]), pageNum: pageNum + 1, showToastState: list.length != res.total })
          } else {
            if (pageNum == 1) {
              this.setData({ list: []})
            }
            this.setData({showToastState:false})
        }
          this.setData({ isRequst: false, total: res.total })
        if (showLoading) { this.setData({ showLoading: false})}
      })
      } else {
        this.setData({ isRequst: false })
      }
    }
  },
  showSelect(state){ // 显示/隐藏筛选
    this.setData({ showSelectState: state != null ? state:!this.data.showSelectState})
  },
  getIndex(e){
    let d = e.currentTarget.dataset
    let { searchArr} = this.data
    if (d.type == 'result') {
      this.setData({ searchArr: [0, -1, -1, -1, -1, -1, -1]})
    } else {
      d.type = Number(d.type)
      if (d.type == 3) {
        this.setData({ [`searchArr[4]`]: -1 })
        this.setData({ ...app._processingAreaData([(d.index == searchArr[d.type] ? 0 : d.index), 0, 0]) })
      }
      this.setData({ [`searchArr[${d.type}]`]: searchArr[d.type] != d.index ? d.index : (d.type == 0?d.index:-1)})
      if (d.type == 0) {
        this.setData({ pageNum:1 })
        this.saveChange(false)
      }
    }
  },
  returnFalse(){
    return false;
  },
  saveChange(state){
    if (typeof (state) == 'boolean') {
      this.showSelect(state)
      this.setCurrencyData()
    }else{
      this.showSelect()
      this.setCurrencyData(true)
    }
  },
  //获取搜索框的值
  bindKeyInput: function (e) {
    // wx.navigateTo({ url: '/pages/apply_search/index' })
    this.setData({ searchValue: e.detail.value.replace(/\s+/g, "").replace(/[\-\_\,\!\|\~\`\(\)\#\$\%\^\&\*\{\}\:\;\"\<\>\?]/g, '')})
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.feach(true)
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this._getMatchList()
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  toDetail(e) {
    wx.navigateTo({ url: '/pages/competition_detail/index?id=' + e.detail.currentTarget.dataset.id })
  }
})